package softserve.vgolosh;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import softserve.vgolosh.utils.FileUtil;

import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException;

public class JdbcConnect {
	private static List<String> clientSql = new ArrayList<String>();
	static {
		clientSql.add("SET @ratingRange = 5;");
		clientSql.add("SET @feedbackRange = 2;");
	}
	public static String URL = "jdbc:mysql://localhost/";
	private Connection conn;

	public JdbcConnect() throws InstantiationException, IllegalAccessException,
			ClassNotFoundException, SQLException {
		Class.forName("com.mysql.jdbc.Driver").newInstance();
		conn = DriverManager.getConnection(URL, "root", "root");
		conn.close();
	}

	public void addClients(String rootDir) throws IOException {
		List<String> scriptContents = FileUtil.getContents("addClient.txt");
		List<String> clientNames = FileUtil.getClientNames(rootDir);
		String sqlVar = new String();
		System.out.println(clientNames);
		for (String clientName : clientNames) {
			sqlVar = "SET @customerName = '" + clientName+"'";
			List<String> executable = new ArrayList<String>();
			executable.add(sqlVar);
			executable.addAll(clientSql);
			executable.addAll(scriptContents);
			System.out.println("Adding client " + clientName);
			executeSQL(executable);	
		}
	}

	public void executeSQL(List<String> fileContents) {
		Statement st;
		try {
			conn = DriverManager.getConnection(URL, "root", "root");
			st = conn.createStatement();
			for (String string : fileContents) {
				st.execute(string);
			}
		} catch (MySQLIntegrityConstraintViolationException e) {
			System.out.println("Already added");
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}
